#include "customtoolbutton.h"

#include <QIcon>
#include <QPainter>
#include <QPaintEvent>
#include <QMouseEvent>
#include <QDebug>

CCustomToolButton::CCustomToolButton(QWidget *parent)
    :QToolButton(parent)
    ,m_bToggled(false)
    ,m_bHover(false)
{
    Init();
}

CCustomToolButton::CCustomToolButton(const QIcon &icon, const QString &text, const QString &tip, QWidget *parent)
    :QToolButton(parent)
    ,m_bToggled(false)
    ,m_bHover(false)
{
    setIcon(icon);
    setText(text);
    setToolTip(tip);
    Init();
}

void CCustomToolButton::mousePressEvent(QMouseEvent *e)
{
    Q_UNUSED(e)
    QToolButton::mousePressEvent(e);
}

void CCustomToolButton::mouseReleaseEvent(QMouseEvent *e)
{
    QToolButton::mouseReleaseEvent(e);
    if (Qt::LeftButton == e->button())
    {
        m_bToggled = isCheckable() && isChecked();
    }
}

void CCustomToolButton::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event)
    QPainter painter(this);
    //paint.save();
    QRect bgRect = rect().adjusted(1, 1, -1, -1); // 留1px边距
    painter.setRenderHint(QPainter::Antialiasing);
    painter.setPen(Qt::NoPen);
    if (isChecked())
    {
        painter.setBrush(QColor(10, 89, 247)); // 选中/按下状态
    }
    else if (m_bHover && isEnabled())
    {
        painter.setBrush(QColor(206, 222, 253)); // 选中/按下状态
    }
    else
    {
        painter.setBrush(QColor(255, 255, 255)); // 正常状态
    }
    //paint.setBrush(brush);
    painter.drawRoundedRect(bgRect, 6, 6);

    // 绘制图标 - 完全手动绘制，避免样式干扰
    if (!icon().isNull()) {
        QIcon::Mode mode = isEnabled() ? QIcon::Normal : QIcon::Disabled;
        QPixmap pixmap = icon().pixmap(20, 20, mode);
        painter.drawPixmap(
            (width() - pixmap.width()) / 2,
            (height() - pixmap.height()) / 2,
            pixmap
        );
    }
    //paint.restore();
    //QToolButton::paintEvent(event);
}

void CCustomToolButton::enterEvent(QEvent *)
{
    m_bHover = true;
}

void CCustomToolButton::leaveEvent(QEvent *)
{
    m_bHover = false;
}

void CCustomToolButton::Init()
{
    setAutoRaise(false);
    setFixedSize(30, 30);
    setAttribute(Qt::WA_TranslucentBackground);
    setToolButtonStyle(Qt::ToolButtonIconOnly);
}
